<?php

namespace App\Http\Controllers;


use App\ComboRefundLog;
use App\Http\Controllers\Admin\Business\Repository\Combo;
use App\Http\Controllers\Admin\Business\Repository\ComboOrder;
use App\Http\Controllers\Admin\Finance\Repository\Commission;
use App\Http\Controllers\Admin\Finance\Repository\Withdraw;
use App\Http\Controllers\Admin\Member\Repository\Member;
use App\MemberPrize;
use App\Models\MemberExchange;
use App\PayOrder;
use App\PrizeSetting;
use App\Repositories\DeviceRepository;
use App\Repositories\DistributeRepository;
use App\Repositories\PacketRepository;
use App\Repositories\UserRepository;
use App\Theme;
use App\Writing;

use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Mockery\Exception;

class UserController extends Controller
{
    private $user;

    public function index()
    {//用户首页

        $user = Auth::guard('member')->user();

        return view('web.user.index', compact('user'));
    }

    public function qrcode()
    {
        $distri = new DistributeRepository();
        $user = Auth::guard('member')->user();
        $url = $distri->getWechatQrcode($user->id);

        return view('web.user.qrcode', compact('user', 'url'));
    }
    public function ticketQrcode(Request $request){
        $out_trade_no=$request->out_trade_no;
        $comboOrder=ComboOrder::where('outTradeNo',$out_trade_no)->firstOrFail();
        return view('web.user.ticket',compact('comboOrder'));
    }
    //别人观看的二维码
    public function userQrcode($user_id)
    {
        $distri = new DistributeRepository();
        $user = Member::findOrFail($user_id);
        $url = $distri->getWechatQrcode($user->id);

        return view('web.user.qrcode', compact('user', 'url'));
    }
    //判断是否抽过奖
    public function choujiang(Request $request){
        $outTradeNo=$request->out_trade_no;
        $payOrder = PayOrder::where('out_trade_no', $request->out_trade_no)->first();
        if($payOrder->is_choujiang==1){
            return 'error';
        }else{
            $payOrder->is_choujiang=1;
            $payOrder->save();
            return 'success';
        }
    }


    //我的套餐
    public function combo(Request $request)
    {
        $out_trade_no=$request->out_trade_no;
        if ($request->out_trade_no) {
            $payOrder = PayOrder::where('out_trade_no', $request->out_trade_no)->first();
            if ($payOrder) {
                $memberPrice = MemberPrize::where('order_id', $payOrder->id)
                    ->where('member_id', Auth::guard('member')->id())
                    ->first();
                if ($memberPrice) {
                    return redirect()->route('member_prize', ['id' => $memberPrice->id,'out_trade_no'=>$out_trade_no,'pay_order'=>$payOrder]);
                } else {
                    $zhong=false;
                    return view('web.user.memberPrizeRecode', compact('memberPrice','zhong','out_trade_no','payOrder'));
                }
            }
        }
        $UserRepository = new UserRepository();
        $combos = $UserRepository->myCombo(Auth::guard('member')->user());
        //dd($combos);
        return view('web.user.combo', compact('combos'));
    }

    //中奖信息
    public function member_prize(Request $request)
    {
        $id = $request->id;
        $out_trade_no=$request->out_trade_no;
        if ($id) {
            $memberPrice = MemberPrize::where('id', $id)
                ->where('member_id', Auth::guard('member')->id())
                ->first();
            if ($memberPrice) {
                $zhong=1;
                return view('web.user.memberPrizeRecode', compact('memberPrice','zhong','out_trade_no'));
            }
        }
    }

    public function user_prizes(Request $request)
    {
        $isExchange = $request->isExchange ?? '0';
        $memberPrize = MemberPrize::where('is_exchange', $isExchange)
            ->where('member_id', Auth::guard('member')->id())
            ->get();
        return view('web.user.user_prizes', compact('isExchange', 'memberPrize'));
    }

    //我的团队
    public function group()
    {
        $UserRepository = new UserRepository();
        $count = $UserRepository->getGroupCount(Auth::guard('member')->user());
        return view('web.user.group', compact('count'));
    }

    public function ajaxGroup(Request $request)
    {

        return Member::where('pid', Auth::guard('member')->id())->paginate(15);

    }

    public function profile(Request $request)
    {

        $user_id = $this->user = Auth::guard('member')->user()->id;
        $member = new \App\Http\Controllers\Admin\Member\Service\Member();
        $user = $member->getMember($user_id);
        if ($request->isMethod('post')) {
            $mobile = $request->post('mobile');
            if (!preg_match('/^0?(13|14|15|17|18)[0-9]{9}$/', $mobile)) {
                return ['code' => -1, 'info' => '请输入正确的号码'];
            }
            $id_number=$request->post('id_number');
            if(!preg_match('/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/',$id_number)){
                return ['code'=>-1,'info'=>'请输入正确的身份证号'];
            }
            $truename=$request->post('truename');
            if ($truename==''){

                return ['code'=>-1,'info'=>'请输入你的真实姓名'];
            }
            $res = UserRepository::editInfo($request->post());
            if ($res) {
                if($request->return_url){
                    return ['code' => 1, 'info' => '操作成功','url'=>$request->return_url];
                }
                return ['code' => 1, 'info' => '操作成功','url'=>''];
            }
            else
                return ['code' => -1, 'info' => '网络繁忙'];
        }

        return view('web.user.profile', ['user' => $user,'return_url'=>$request->return_url]);
    }

    public function withdrawals()
    {
        return view('web.user.withdrawals');
    }

    public function withdrawalsStore(Request $request)
    {
        $user = Auth::guard('member')->user();
        $this->validate(
            $request, [
                'price' => 'required|numeric|min:5' ,
              /*  'bank_id' => 'required|numeric',*/
                'username' => 'required',
            ]
        );
        \Cache::forever('bank_id'.$user->id,$request->bank_id);
        \Cache::forever('username'.$user->id,$request->username);
        //用户正在提现的

        if($user->wallet_push_money-$request->price<0){
            return redirect()->back()->withErrors('你的余额不足');
        }
        Member::where('id',$user->id)->decrement('wallet_push_money',$request->price);
        Member::where('id',$user->id)->increment('wallet_used_push_money',$request->price);
        $withdraw = new Withdraw();

        if($request->price<100&&$request->price>5){
            $withdraw->price = $request->price-5;
            $withdraw->poundage=5;
        }else{
            $withdraw->price = $request->price;
        }

        $withdraw->username = $request->username;
        $withdraw->bank_id = $request->bank_id;
        $withdraw->type = 2;
        $withdraw->member_id = $user->id;
        $withdraw->save();

        return redirect()->route('user_withdrawalsDetail', ['id' => $withdraw->id]);
    }

    public function withdrawalsDetail($id)
    {

        $detail = Withdraw::where('member_id', Auth::guard('member')->id())
            ->where('id', $id)->firstOrFail();

        $status = config('withdrawals.status');

        return view('web.user.withdrawalsDetail', compact('detail', 'status'));
    }

    public function record()
    {//提成记录
        $user = Auth::guard('member')->user();

        return view('web.user.record', compact('user'));
    }

    public function ajaxRecord()
    {

        $UserRepository = new UserRepository();

        return $UserRepository->getRecord();
    }

    //提现记录
    public function presentRecord()
    {
        $userRepository = new UserRepository();
        $count = $userRepository->getPresentRecordCount();
        return view('web.user.txjl', compact('count'));
    }

    public function ajaxPresentRecord()
    {

        $UserRepository = new UserRepository();
        return $UserRepository->getPresentRecord();
    }

    //工作人员扫码
    public function memberPrize(Request $request)
    {
        if ($request->sign) {
            try {
                $sign = decrypt($request->sign);
                $sign = unserialize($sign);
            } catch (DecryptException $exception) {
                abort('403', '地址参数不正确');
            }
        }
        $auth = Auth::guard('member')->user();
        //dd($auth);
        //判断是不是工作人员
        if ($auth->is_worker) {
            $memberPrize = MemberPrize::find($sign['memberPrize_id']);
            if ($memberPrize->is_exchange == 1) {
                abort('403', '已经领取过奖品');
            }
            $memberPrize->is_exchange = 1;
            $memberPrize->worker_id = $auth->id;
            $memberPrize->save();
            return view('web.user.prizeRecode', compact('memberPrize'));
        } else {
            abort('403', '你没有权限操作');
        }
    }

    //用户得奖的二维码
    public function prizeCode(Request $request)
    {
        // $user=Auth::guard('member')->user();
        $memberPrize = MemberPrize::find(1);
        $prizeSetting = new PrizeSetting();
        $image = $prizeSetting->prizeQrcode($memberPrize);
        return view('web.user.prizeCode', compact('image'));
    }

    //用户套餐退款设定
    public function comboRefund(Request $request)
    {


        //套餐id
        $outTradeNo = $request->outTradeNo ?? '';
        $comboOrder = ComboOrder::where('outTradeNo', $outTradeNo)->where('member_id', Auth::guard('member')->id())->firstOrFail();

        if ($comboOrder->is_refund == 1) {
            return response()->json(
                [
                    'code' => 0,
                    'msg' => '此套餐已经退款'
                ]);

        }
        //查询用户旅游的次数
        $userTimes = Auth::guard('member')->user()->wallet_spots;

        if ($userTimes < $comboOrder->times) {
            return response()->json(
                [
                    'code' => 0,
                    'msg' => '此套餐已经被使用,不能退款'
                ]);

        }
        //计算需要退款的余额
        $orderModel = new \App\Http\Controllers\Admin\Business\Service\ComboOrder();
        //查出订单
        $order = $orderModel->getComboOrder($comboOrder->id);
        //计算分销价格
        $rateAry = get_real_rate($order);
        $parentMoney = $order->price * $rateAry['rate'] / 100;
        $topMoney = $order->price * $rateAry['top_rate'] / 100;
        $refundMoney = $comboOrder->price - $parentMoney - $topMoney;
        if ($refundMoney <= 0) {
            return response()->json([
                'code' => 0,
                'msg' => '你的钱被分光了'
            ]);

        }
        //微信退款api
        $packetRepository = new PacketRepository();
        $packetRepository->merchantPay(Auth::guard('member')->user(), $refundMoney, '套餐退款');

        //改变退款状态
        $comboOrder->is_refund = 1;
        $comboOrder->save();
        //减去用户表的使用次数
        $member = \App\Member::find(Auth::guard('member')->id());
        $member->decrement('wallet_spots', $comboOrder->times);
        //写入退款记录表
        $combo = Combo::findOrFail($comboOrder->combo_id);
        $comboRefundLog = new ComboRefundLog();
        $comboRefundLog->member_id = $member->id;
        $comboRefundLog->refund_money = $refundMoney;
        $comboRefundLog->combo_name = $combo->title;
        $comboRefundLog->combo_id = $combo->id;
        $comboRefundLog->save();
        return response()->json([
            'code' => 1,
            'msg' => '退款成功',
        ]);
    }
    //兑换套餐列表
    public function exchange(){
      $exchange=  MemberExchange::join('combo_exchange','combo_exchange.id','=','member_exchange.exchange_id')
            ->join('combos','combos.id','=','combo_exchange.combo_id')
            ->where('member_exchange.member_id',Auth::guard('member')->id())
            ->select('combos.*','combo_exchange.code','member_exchange.created_at')
            ->orderBy('member_exchange.created_at','desc')
            ->get();
        
        return view('web.user.exchange',compact('exchange'));
    }
}
